package jiwei.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.TransactionAttributeSource;

import javax.sql.DataSource;

@Configuration //配置类
//@ComponentScan(basePackages = {"jiwei"}) //开启组件扫描
@ComponentScan(value = "jiwei",
        excludeFilters = {@Filter(type = FilterType.REGEX, pattern = "jiwei.service.xml.*")}
) //组件扫描
@EnableTransactionManagement
public class DbConfig {
    //数据库连接池
    @Bean(name = "dataSource")
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    //JdbcTemplate对象
    @Bean(name = "jdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier(value = "dataSource") DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //注入dataSource。在ioc容器中根据类型找到dataSource。
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //创建事务管理器
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier(value = "dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /*事务属性源
    方法名，transactionAttributeSource()可以；getTransactionAttributeSource()不可以
    1，
    @Bean(name = "transactionAttributeSource")
    public TransactionAttributeSource getTransactionAttributeSource() {
    2，
    @Bean
    public TransactionAttributeSource transactionAttributeSource() {
    3，
    @Bean 不设置name，则name默认为 方法名。
    name 应该是等同于 id。<bean id=
    */
    @Bean(name = "transactionAttributeSource")
    public TransactionAttributeSource transactionAttributeSource() {
        return new AnnotationTransactionAttributeSource(false);
    }
}
